package com;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

@WebServlet("/prod/*") // 捕获所有路径
/**
 * 示例 请求的地址： http://10.20.255.35:8081/transpond-1.0-SNAPSHOT/prod/proxy/api/API_YX/proWoProcess/queryMajorOrder
 * 实际访问 目标地址： http://10.224.158.101:8182/API_YX/proWoProcess/queryMajorOrder
 *
 * 捕获所有路径：/prod/*
 */
public class ProxyServletProd extends HttpServlet {
    //    private static final String TARGET_SERVER = "http://127.0.0.1:8080";
//    测试环境
//    private static final String TARGET_SERVER = "http://10.224.158.64:8282/proxy/api";
    //    生产环境
    private static final String TARGET_SERVER = "http://10.224.158.101:8182";
    private CloseableHttpClient httpClient;
    // 需要过滤的敏感头列表（根据业务需求调整）
    private static final List<String> EXCLUDED_HEADERS = Arrays.asList(
            "cookie", "authorization", "content-length", "host"
    );

    @Override
    public void init() {
        httpClient = HttpClients.createDefault();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            System.out.println("ProxyServlet.service.....");
            // 1. 构建目标URL
            String requestURI = req.getRequestURI();
            if (requestURI.contains("/prod")){
                requestURI = requestURI.substring(requestURI.lastIndexOf("/prod")+5);
            }
            String targetUrl = TARGET_SERVER + requestURI;
            if (req.getQueryString() != null) {
                targetUrl += "?" + req.getQueryString();
            }
            System.out.println("targetUrl："+targetUrl);
            // 2. 创建对应方法的HTTP请求
            HttpRequestBase httpRequest = createRequest(req, targetUrl);
            // 3. 设置请求头（从原始请求中复制）
            Enumeration<String> headerNames = req.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String lowerHeader = headerName.toLowerCase();

                // 跳过敏感头和协议相关头
                if (EXCLUDED_HEADERS.contains(lowerHeader)) continue;

                // 复制多值头
                Enumeration<String> values = req.getHeaders(headerName);
                while (values.hasMoreElements()) {
                    httpRequest.addHeader(headerName, values.nextElement());
                }
            }

            // 特殊处理 Content-Type
            String contentType = req.getContentType();
            if (contentType != null && !contentType.isEmpty()) {
                httpRequest.setHeader("Content-Type", contentType);
            }

            // 4. 复制POST请求的参数
            if (httpRequest instanceof HttpPost) {
                HttpPost httpPost = (HttpPost) httpRequest;

                // 读取原始请求的输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
                StringBuilder requestBody = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }

                // 如果有请求体，则设置到代理请求中
                if (requestBody.length() > 0) {
                    StringEntity entity = new StringEntity(requestBody.toString(), "UTF-8");
                    entity.setContentType(req.getContentType()); // 保留原始内容类型
                    httpPost.setEntity(entity);
                }
            }
            // 3. 执行请求并返回响应
            try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
                resp.setStatus(response.getStatusLine().getStatusCode());
//                // 复制响应头
//                Arrays.stream(response.getAllHeaders())
//                        .forEach(h -> resp.addHeader(h.getName(), h.getValue()));

                response.getEntity().writeTo(resp.getOutputStream());
            }
        } catch (Exception e) {
            resp.sendError(500, "Proxy Error: " + e.getMessage());
            System.out.println("error!!.....");
        }
    }

    // 根据请求方法创建对应对象
    private HttpRequestBase createRequest(HttpServletRequest req, String url) {
        switch (req.getMethod().toUpperCase()) {
            case "GET":
                return new HttpGet(url);
            case "POST":
                return new HttpPost(url);
            case "PUT":
                return new HttpPut(url);
            case "DELETE":
                return new HttpDelete(url);
            default:
                throw new UnsupportedOperationException("Method not supported");
        }
    }

    @Override
    public void destroy() {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}